import React, { useEffect, useState } from 'react'
import { Button, Space, Tabs } from 'antd'
// import cn from 'classnames'
// import { usePathname } from 'next/navigation'
import useSwr from 'swr'
import {
  RiAddBoxLine,
} from '@remixicon/react'
import UserCard from '../base/userCard'
import AddArea from './addArea'
import type { AppListResponse } from '@/models/app'
import type { PluginProvider } from '@/models/common'
import { getTenants } from '@/service/common'
import type { OpenTypes } from '@/app/(commonLayout)/apps/component/base/createModal'
import CreateModal from '@/app/(commonLayout)/apps/component/base/createModal'
type Props = {
  data?: AppListResponse | undefined
  plugins?: PluginProvider[] | undefined
  mutate?: () => void
  pluginsMutate?: () => void
  setActiveTab?: (newActiveTab: string) => void
  setCallback?: any
}

type AreaNameListItem = {
  id: string
  name: string
  status: string
  created_at: string
  current: boolean
}

type areaNameItem = {
  key: string
  name: string
}

const AreaPage: React.FC<Props> = (props) => {
  const { data, plugins, setActiveTab, mutate, pluginsMutate, setCallback } = props
  const [openModal, setOpenModal] = useState<boolean>(false)
  // const pathName = usePathname()
  const [activeArea, setActiveArea] = useState<any>('')
  const [tabClick, setTabClick] = useState<string>('1')
  const [isAddOpen, setIsAddOpen] = useState<OpenTypes>({
    isOpen: false,
    title: '',
  })
  const [header_image, setHeaderImage] = useState('agent')
  const [areaName, setAreaName] = useState<Array<areaNameItem>>([])

  const { data: tenants, mutate: tenantsMutate }: any = useSwr('/getTenants', getTenants)
  useEffect(() => {
    if (tenants) {
      const newArr: any = []
      const defaultSpace = tenants?.find((item: any) => item.current === true)
      setActiveArea(defaultSpace.id)
      setCallback(defaultSpace.id)
      tenants.forEach((item: AreaNameListItem, index: any) => {
        newArr.push({ key: item.id, name: item.name })
      })
      setAreaName(newArr)
    }
  }, [tenants])

  // const areaName = [
  //   {
  //     key: 1,
  //     name: '默认空间',
  //   },
  //   {
  //     key: 2,
  //     name: '项目空间1',
  //   },
  //   {
  //     key: 3,
  //     name: '项目空间2',
  //   },
  //   {
  //     key: 4,
  //     name: '项目空间4',
  //   },
  // ]
  const operations = () => {
    return <Space>
      {/* <Button type="primary" disabled>{`上架${tabClick === '1' ? 'Agent' : tabClick === '2' ? '插件' : tabClick === '3' ? '工作流' : '多智能体'}`}</Button> */}
      <div className='flex items-center justify-center text-18 text-#216EFF cursor-pointer color-#216EFF' onClick={() => {
        const mode = tabClick === '1' ? 'agent-chat' : tabClick === '2' ? 'chat' : tabClick === '3' ? 'workflow' : 'metabolic'
        setIsAddOpen({
          isOpen: true,
          title: `创建${tabClick === '1' ? 'Agent' : tabClick === '2' ? '插件' : tabClick === '3' ? '工作流' : '多智能体'}`,
          titleName: `${tabClick === '1' ? 'Agent' : tabClick === '2' ? '插件' : tabClick === '3' ? '工作流' : '多智能体'}`,
          mode,
        })
        const headerImg = tabClick === '1' ? 'agent' : tabClick === '2' ? 'chat' : tabClick === '3' ? 'workflow' : 'metabolic'
        setHeaderImage(headerImg)
      }}><RiAddBoxLine style={{ width: '20px', height: '20px', color: '#216EFF', marginRight: '5px' }} /><p style={{ color: '#216EFF' }}>{`创建${tabClick === '1' ? 'Agent' : tabClick === '2' ? '插件' : tabClick === '3' ? '工作流' : '多智能体'}`}</p></div>
    </Space>
  }
  //   width: 88px;
  // height: 24px;
  // font-family: PingFangSC, PingFang SC;
  // font-weight: 500;
  // font-size: 18px;
  // color: #216EFF;
  // line-height: 25px;
  // text-align: right;
  // font-style: normal;

  const items = [
    {
      label: 'Agent',
      key: '1',
      children: <div className='flex-1 w-[100%] overflow-y-auto' style={{ height: 'calc(100vh - 268px)' }}>
        <div className='flex flex-1 flex-wrap overflow-hidden overflow-y-auto    gap-[1.45vw]'>
          {data?.data?.filter(i => i.mode === 'agent-chat' && tabClick === '1').map((item, index) => (
            <UserCard
              headerImag='header_agent1'
              mutate={mutate}
              key={index}
              data={item}
              areaList={areaName}
              tabClick={tabClick}
              activeArea={activeArea}
              currentTab='agent'
            // styleCss={{ backgroundImage: 'url(\'/agent-platform-web/bg/agentBg1.png\')' }}
            />
          ))}
        </div>
      </div>,
    },
    {
      label: '插件',
      key: '2',
      children: <div className='flex-1 w-[100%] overflow-y-auto' style={{ height: 'calc(100vh - 268px)' }}>
        <div className='flex flex-1 flex-wrap overflow-hidden overflow-y-auto  gap-[1.45vw]'>
          {plugins?.map((item, index) => (
            <UserCard
              headerImag='header_chat1'
              mutate={pluginsMutate}
              key={index}
              plugin={item}
              areaList={areaName}
              tabClick={tabClick}
              activeArea={activeArea}
              currentTab='chat'
            // styleCss={{ backgroundImage: 'url(\'/agent-platform-web/bg/agentBg2.png\')' }}
            />),
          )}
        </div>
      </div>,
    },
    {
      label: '工作流',
      key: '3',
      children: <div className='flex-1 w-[100%] overflow-y-auto' style={{ height: 'calc(100vh - 268px)' }}>
        <div className='flex flex-1 flex-wrap overflow-hidden overflow-y-auto  gap-[1.45vw]'>
          {data?.data?.filter(i => i.mode === 'workflow' && tabClick === '3').map((item, index) => (
            <UserCard
              headerImag='header_workflow1'
              mutate={mutate}
              key={index}
              data={item}
              areaList={areaName}
              tabClick={tabClick}
              activeArea={activeArea}
              currentTab='workflow'
            // styleCss={{ backgroundImage: 'url(\'/agent-platform-web/bg/agentBg3.png\')' }}
            />
          ))}
        </div>
      </div>,
    },
    {
      label: '多智能体',
      key: '4',
      children: <div className='flex-1 w-[100%] overflow-y-auto' style={{ height: 'calc(100vh - 268px)' }}>
        <div className='flex flex-1 flex-wrap overflow-hidden overflow-y-auto  gap-[1.45vw]'>
          {data?.data?.filter(i => i.mode === 'metabolic' && tabClick === '4').map((item, index) => (
            <UserCard
              headerImag='header_agent1'//UI未出图，暂用agent
              mutate={mutate}
              key={index}
              data={item}
              areaList={areaName}
              tabClick={tabClick}
              activeArea={activeArea}
              currentTab='metabolic'
            // styleCss={{ backgroundImage: 'url(\'/agent-platform-web/bg/agentBg3.png\')' }}
            />
          ))}
        </div>
      </div>,
    },
  ]
  return (
    <>
      <div className='mt-[24px]'>
        <div className='flex' style={{ justifyContent: 'space-between' }}>
          <div className='text-[#1C2748] text-[20px] mb-[16px]'>个人空间</div>
          <Button onClick={() => {
            setActiveTab?.('release')
          }}>发布管理</Button>
        </div>
        {/* <div className='flex justify-between py-[17px] px-[28px] bg-[#fff] mb-[18px] rounded-[8px]'>
          <div className='flex'>
            {tenants?.map((item: any) => (
              <div key={item.id}
                className={cn('my-auto py-[6px] px-[20px] mr-[24px] border rounded-[4px] cursor-pointer',
                  activeArea === item.id
                    ? 'border-[#216EFF] bg-[rgba(33,110,255,0.1)] text-[#216EFF]'
                    : 'border-[#BBBDC0] text-[#BBBDC0]',
                )}
                onClick={() => {
                  setActiveArea(item.id)
                  setCallback(item.id)
                }}>
                {item.name}
              </div>
            ))}
          </div> */}
        {/* <Space>
            <Image src={setEdit} alt='img' width={30} className='mr-[10px] h-[30px] my-auto cursor-pointer' onClick={() => {
              history.pushState(null, '', `${pathName}?category=detail`)
              setActiveTab?.('detail')
            }} />
            <Image src={add} alt='img' width={30} className='h-[30px] my-auto cursor-pointer' onClick={() => setOpenModal(true)} />
          </Space> */}
        {/* </div> */}
        <div className='bg-[#fff] rounded-[8px] px-[24px]'
          style={{ height: 'calc(100vh - 158px)' }}
        >
          <Tabs tabBarExtraContent={operations()} items={items} onChange={(val) => { setTabClick(val) }} />
        </div>
      </div>
      <AddArea modalState={openModal} onClose={(val: boolean) => setOpenModal(val)} />
      {isAddOpen.isOpen
        ? <CreateModal categoryTenants={true} tenant_id={activeArea} isAddOpen={isAddOpen} onClose={(val: boolean) => setIsAddOpen({ ...isAddOpen, isOpen: val })} />
        : null}
    </>
  )
}

export default AreaPage
